<template>

  <div class="container">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="nav-title">水位站详情</div>
    </div>

    <!-- 站点头部 -->
    <div class="station-header">
      <div class="station-name">{{ stationName }}</div>
      <van-field
        v-model="selectedFlagText"
        label="统计周期"
        class="flag-select"
        readonly
        clickable
        placeholder="请选择"
        @click="showFlagPicker = true"
      />
      <van-popup v-model="showFlagPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="flagOptions"
          @confirm="onConfirmFlag"
          @cancel="showFlagPicker = false"
        />
      </van-popup>
    </div>

    <!-- 水位图表区域 -->
    <div class="chart-section">
      <div class="chart-title">{{ fType == 1?'流量':'水位' }}变化趋势</div>
      <div class="chart-container">
        <div id="waterLevelChart" />
      </div>
    </div>

    <!-- 水位数据表格 -->
    <div class="data-section">
      <div class="chart-title">站点数据</div>
      <div class="table-container">

        <van-empty
          v-if="waterData.length === 0"
          description="暂无结果"
          class="empty-state"
        />
        <table v-else class="data-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>水位(m)</th>
              <th>流量(m³/s)</th>
              <th>预报水深(m)</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in waterData" :key="index">
              <td>{{ item.fTime }}</td>
              <td>
                <span v-if="item.fType == 0">
                  <span :class="item.swFlag=='↑'?'trend-up':(item.swFlag=='↓'?'trend-down':'trend-even')">{{ item.sw }}{{ item.swFlag }}</span>

                </span>
                <span v-else>-</span>
              </td>
              <td>
                <div>{{ item.flowOut }}<span v-if="item.fType == 1">(出)</span></div>
                <div>{{ item.flowIn }}<span v-if="item.fType == 1">(进)</span></div>
              </td>
              <td>{{ item.ybss }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { pushShowRegimenDetail } from '@/api/mobile/index'
import echarts from 'echarts'

export default {
  name: 'RegimenDetial',
  data() {
    return {
      comparePrevious: false,
      selectedFlag: 'week',
      selectedFlagText: '周',
      showFlagPicker: false,
      flagOptions: [
        { text: '周', value: 'week' },
        { text: '日', value: 'day' }
      ],
      waterLevelChart: null,
      stationName: '',
      waterData: [],
      predictionData: [],
      fType: '0'
    }
  },
  mounted() {
    this.parseUrlParams()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    // 解析URL参数
    async parseUrlParams() {
      // 获取查询参数
      const queryString = window.location.search
      this.queryParams = queryString
      // 解析查询参数
      const params = new URLSearchParams(queryString)
      if (params.has('fName')) {
        this.stationName = decodeURIComponent(params.get('fName'))
        const res = await pushShowRegimenDetail({ fName: this.stationName, flag: this.selectedFlag })
        this.waterData = res.data
        this.predictionData = res.prediction
        this.fType = res.data[0].fType
        if (this.fType === '1') {
          this.initChartFlow()
        } else {
          this.initChartSW()
        }
        window.addEventListener('resize', this.resizeChart)
      } else {
        this.$toast('url不合法，获取参数失败')
      }
    },
    formatChartDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours() ? date.getHours() + ':00' : ''}`
    },
    initChartFlow() {
      const chartDom = document.getElementById('waterLevelChart')
      if (!chartDom) return

      this.waterLevelChart = echarts.init(chartDom)

      // 处理历史数据（实线部分）
      const historyData = this.waterData
        .map(item => ({
          time: new Date(item.fTime),
          flowIn: parseFloat(item.flowIn),
          flowOut: parseFloat(item.flowOut),
          label: `${this.formatChartDate(item.fTime)}`
        }))
        .sort((a, b) => a.time - b.time)

      // 准备图表数据
      const historyTimes = historyData.map(d => d.label)

      const flowInData = historyData.map(d => d.flowIn)
      const flowOutData = historyData.map(d => d.flowOut)
      // 最大值
      const max = Math.max(...[...flowInData, ...flowOutData])
      // 最小值
      const min = Math.max(...[...flowInData, ...flowOutData])
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = params[0].axisValue
            return `${date} (m³/s)<br/>${params[0].seriesName}: ${params[0].value} <br/>${params[1].seriesName}: ${params[1].value}`
          }
        },
        legend: {
          show: true,
          data: ['入库流量', '出库流量'],
          bottom: 0
        },
        grid: {
          right: '20',
          bottom: '20',
          left: '0',
          top: '30',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: historyTimes,
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          axisLabel: {
            rotate: 45,
            formatter: function(value, index) {
              // 简化显示，只显示日期部分
              return value.slice(0, 5)
            },
            textStyle: {
              fontSize: 8
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '流量(m³/s)',
          nameTextStyle: {
            color: '#7f8c8d',
            padding: [0, 0, 0, 30]
          },
          min: min,
          max: max,
          // interval: 0.2,
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f6ff'
            }
          }
        },
        series: [{
          name: '入库流量',
          type: 'line',
          data: flowInData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#1a2980',
            type: 'solid'
          },
          itemStyle: {
            color: '#1a2980'
          }
        },
        {
          name: '出库流量',
          type: 'line',
          data: flowOutData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#9eca7f',
            type: 'solid'
          },
          itemStyle: {
            color: '#9eca7f'
          }
        }]
      }
      this.waterLevelChart.setOption(option)
    },
    initChartSW() {
      const chartDom = document.getElementById('waterLevelChart')
      if (!chartDom) return

      this.waterLevelChart = echarts.init(chartDom)

      // 处理历史数据（实线部分）
      const historyData = this.waterData
        .map(item => ({
          time: new Date(item.fTime),
          value: parseFloat(item.sw),
          label: `${this.formatChartDate(item.fTime)}`
        }))
        .sort((a, b) => a.time - b.time)

      // 处理预测数据（虚线部分）
      const predictionData = this.predictionData
        .map(item => ({
          time: new Date(item.fTime),
          value: parseFloat(item.sw),
          label: `${this.formatChartDate(item.fTime)}`
        }))
        .sort((a, b) => a.time - b.time)

      // 为了连接自然，添加最后一个历史数据点作为预测的起点
      // if (historyData.length > 0 && predictionData.length > 0) {
      //   predictionData.unshift({
      //     time: historyData[historyData.length - 1].time,
      //     value: historyData[historyData.length - 1].value,
      //     label: historyData[historyData.length - 1].label
      //   })
      // }

      // 准备图表数据
      const historyTimes = historyData.map(d => d.label)
      const historyLevels = historyData.map(d => d.value)

      const predictionTimes = predictionData.map(d => d.label)
      let predictionLevels = predictionData.map(d => d.value)
      if (predictionLevels.length) {
        predictionLevels = [...historyLevels, ...predictionLevels]
      } else {
        predictionLevels = [...historyLevels]
      }
      // 最大值
      const max = Math.max(...predictionLevels)
      // 最小值
      const min = Math.min(...predictionLevels)
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const seriesName = params[0].seriesName
            const value = params[0].value
            const date = params[0].axisValue

            if (seriesName === '预测水位') {
              return `${date}<br/>预测水位: ${value} m`
            }
            return `${date}<br/>水位: ${value} m`
          }
        },
        grid: {
          right: '20',
          bottom: '20',
          left: '0',
          top: '5',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [...historyTimes, ...predictionTimes],
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          axisLabel: {
            rotate: 45,
            formatter: function(value, index) {
              // 简化显示，只显示日期部分
              return value.slice(0, 5)
            },
            textStyle: {
              fontSize: 8
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '水位(m)',
          nameTextStyle: {
            color: '#7f8c8d',
            padding: [0, 0, 0, 30]
          },
          min: min,
          max: max,
          // interval: 0.2,
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f6ff'
            }
          }
        },
        series: [
          {
            name: '历史水位',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#1a2980',
              type: 'solid'
            },
            itemStyle: {
              color: '#26d0ce'
            },
            data: historyLevels
          },
          {
            name: '预测水位',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#1a2980',
              type: 'dashed'
            },
            itemStyle: {
              color: '#26d0ce'
            },
            data: predictionLevels
          }
        ]
      }
      this.waterLevelChart.setOption(option)
    },
    resizeChart() {
      if (this.waterLevelChart) {
        this.waterLevelChart.resize()
      }
    },
    onConfirmFlag(value) {
      debugger
      this.selectedFlagText = value.text
      this.selectedFlag = value.value
      this.showFlagPicker = false
      this.parseUrlParams()
    }
  }
}
</script>
<style scoped>
.container {
  max-width: 800px;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 导航栏 */
.nav-bar {
  background: rgb(26, 41, 128) !important;
  color: white;
  padding: 16px;
  display: flex;
  align-items: center;
  position: relative;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
}

/* 站点头部 */
.station-header {
  padding: 10px;
  text-align: center;
  border-bottom: 1px solid #f0f6ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.station-name {
  font-size: 24px;
  font-weight: 700;
  color: #1a2980;
  margin-bottom: 8px;
}

.station-location {
  font-size: 16px;
  color: #7f8c8d;
}

/* 水位图表区域 */
.chart-section {
  padding: 20px 10px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a2980;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.chart-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 18px;
  background: #26d0ce;
  margin-right: 8px;
  border-radius: 2px;
}

.chart-container {
  height: 300px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  padding: 15px;
}

#waterLevelChart {
  width: 100%;
  height: 100%;
}

/* 对比控制区 */
.compare-controls {
  display: flex;
  align-items: center;
  margin: 15px 0 25px;
  padding: 12px 15px;
  background: #f7fbff;
  border-radius: 10px;
  border: 1px solid #e6f0ff;
}

.flag-select {
  width: 150px;
  margin-left: 15px;
}

/* 水位数据表格 */
.data-section {
  margin-top: 20px;
  padding: 0 10px;
}

.table-container {
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.data-table th {
  background: #f0f8ff;
  color: #1a5bb8;
  font-weight: 600;
  padding: 14px 12px;
  text-align: center;
  border-bottom: 2px solid #e6f0ff;
}

.data-table td {
  padding: 12px 10px;
  text-align: center;
  border-bottom: 1px solid #f0f6ff;
}

.data-table tr:last-child td {
  border-bottom: none;
}

.trend-up {
  color: #e74c3c;
  font-weight: bold;
}

.trend-down {
  color: #27ae60;
  font-weight: bold;
}

/* 页脚 */
.footer {
  text-align: center;
  padding: 25px;
  color: #7f8c8d;
  font-size: 14px;
  margin-top: 20px;
  border-top: 1px solid #f0f6ff;
}

.update-time {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 8px;
  font-size: 13px;
}

.update-time .van-icon {
  margin-right: 6px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .station-name {
    font-size: 20px;
  }

  .chart-container {
    padding: 10px;
  }

  .data-table {
    font-size: 14px;
  }

  .data-table th,
  .data-table td {
    padding: 10px 8px;
  }
}
</style>
